package com.aryankh.wordbookfx.controller;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.extra.spring.SpringUtil;
import com.aryankh.wordbookfx.TaxStartApplication;
import com.aryankh.wordbookfx.constant.MouseClickConstants;
import com.aryankh.wordbookfx.constant.PathConstants;
import com.aryankh.wordbookfx.constant.ThemeColorConstants;
import com.aryankh.wordbookfx.entity.ReloadWordEntity;
import com.aryankh.wordbookfx.service.WordService;
import com.aryankh.wordbookfx.view.*;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Paint;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.net.URL;
import java.util.*;

/**
 * @Author AryanKH
 * @Date 2023/4/14 14:11
 */
@FXMLController
public class WordBookMainController implements Initializable {
    String selectedItem = "wordbook";
    //层级map变量

    @FXML
    private ChoiceBox<String> tableDropList;

    @FXML
    private Label currentTable;


    @FXML
    private Text textBox;

    @FXML
    private ToggleButton toggleBtn;

    @FXML
    private Button patchBtn;

    @FXML
    private Button translationBtn;

    @FXML
    private AnchorPane mainBoard;

    @FXML
    private Button countBtn;


    @FXML
    private Button chineseSearchBtn;

    @FXML
    private Button addWordBtn;

    @FXML
    private Button lookupBtn;


    /**
     * EN Box
     *
     * @author AryanKH
     * @date 2023/4/25 16:39
     * @param Text
     */
    @FXML
    private TextField inputBox;

    /**
     * 中文 Box
     *
     * @author AryanKH
     * @date 2023/4/25 16:39
     * @param Text
     */
    @FXML
    private TextField explanationBox;

    @FXML
    private Button randomBtn;


    @FXML
    private ToolBar mainBar;

    private String themeName = "";

    Stage stage = TaxStartApplication.getStage();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        WordService wordService = SpringUtil.getBean(WordService.class);
        stage.setResizable(false);
        stage.setTitle("Word Book");
        wordService.reloadDBFile();
        wordService.reloadTheme(toggleBtn.getText());
        initTableDropList(wordService);
        saveTableName();
        startToggle();
        reLoadTheme();

    }

    private void reLoadTheme() {
        FileReader fileReader = new FileReader(PathConstants.THEME_NAME_PATH);
        if ("LightMode".equals(fileReader.readString())) {
            lightMod();
            toggleBtn.setText("DarkMode");
            // toggleBtn.setSelected(true);
        } else if ("DarkMode".equals(fileReader.readString())) {
            darkMod();
            toggleBtn.setText("LightMode");
            toggleBtn.setSelected(true);
        }
    }

    private void startToggle() {
        toggleBtn.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                themeName = "LightMode";
                toggleBtn.setText(themeName);
                darkMod();
                saveTheme("DarkMode");
            } else {
                themeName = "DarkMode";
                toggleBtn.setText(themeName);
                lightMod();
                saveTheme("LightMode");
            }
        });
    }

    private void lightMod() {
        textBox.setFill(Paint.valueOf(ThemeColorConstants.BLACK));

        countBtn.setTextFill(Paint.valueOf(ThemeColorConstants.BLACK));

        countBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.WHITE), null, null)));

        mainBoard.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.WHITE), null, null)));

        currentTable.setTextFill(Paint.valueOf(ThemeColorConstants.BLACK));

        randomBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.WHITE), null, null)));

        randomBtn.setTextFill(Paint.valueOf(ThemeColorConstants.BLACK));

        mainBar.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.DEEPLY_WHITE), null, null)));

        patchBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.WHITE), null, null)));

        patchBtn.setTextFill(Paint.valueOf(ThemeColorConstants.BLACK));

        translationBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.WHITE), null, null)));

        translationBtn.setTextFill(Paint.valueOf(ThemeColorConstants.BLACK));

        inputBox.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.LIGHT_GRAY), null, null)));
        inputBox.setStyle("-fx-text-fill:#000000;");

        explanationBox.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.LIGHT_GRAY), null, null)));

        explanationBox.setStyle("-fx-text-fill:#000000;");

        chineseSearchBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.LITE_BLACK), null, null)));

        chineseSearchBtn.setStyle("-fx-text-fill:#000000;");

        lookupBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.LITE_BLACK), null, null)));

        lookupBtn.setStyle("-fx-text-fill:#000000;");

        addWordBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.LITE_BLACK), null, null)));

        addWordBtn.setStyle("-fx-text-fill:#000000;");

        tableDropList.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.WHITE), null, null)));

        toggleBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.LITE_BLACK), null, null)));

        toggleBtn.setStyle("-fx-text-fill:#000000;");
    }

    private void darkMod() {
        textBox.setFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));
        textBox.setStyle("-fx-text-fill:#CED0D6;");

        countBtn.setTextFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));

        countBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.PURPLISH_BLACK), null, null)));

        mainBoard.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.PURPLISH_BLACK), null, null)));

        currentTable.setTextFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));

        randomBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.PURPLISH_BLACK), null, null)));

        randomBtn.setTextFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));

        mainBar.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.MODENA_PURPLE), null, null)));

        patchBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.PURPLISH_BLACK), null, null)));

        patchBtn.setTextFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));

        translationBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.PURPLISH_BLACK), null, null)));

        translationBtn.setTextFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));

        inputBox.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.MODENA_PURPLE), null, null)));
        inputBox.setStyle("-fx-text-fill:#CED0D6;");

        explanationBox.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.MODENA_PURPLE), null, null)));

        explanationBox.setStyle("-fx-text-fill:#CED0D6;");

        chineseSearchBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.MODENA_PURPLE), null, null)));

        chineseSearchBtn.setStyle("-fx-text-fill:#CED0D6;  ");

        lookupBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.MODENA_PURPLE), null, null)));

        lookupBtn.setStyle("-fx-text-fill:#CED0D6;");

        addWordBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.MODENA_PURPLE), null, null)));

        addWordBtn.setStyle("-fx-text-fill:#CED0D6;");

        toggleBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.MODENA_PURPLE), null, null)));

        toggleBtn.setStyle("-fx-text-fill:#CED0D6;");

    }

    private void saveTableName() {
        try {
            cn.hutool.core.io.file.FileWriter fileWriter =
                    new cn.hutool.core.io.file.FileWriter(PathConstants.TABLE_NAME_PATH);
            fileWriter.write(selectedItem);
        } catch (Exception e) {

        }
    }

    private void saveTheme(String themeName) {
        try {
            cn.hutool.core.io.file.FileWriter fileWriter =
                    new cn.hutool.core.io.file.FileWriter(PathConstants.THEME_NAME_PATH);
            fileWriter.write(themeName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化DropList
     *
     * @param wordService
     * @author AryanKH
     * @date 2023/5/30 12:55
     */

    private void initTableDropList(WordService wordService) {
        // 初始化dropList
        List<String> tables = wordService.checkAllTableAndCount();
        tables.iterator().forEachRemaining(table -> {
            tableDropList.getItems().add(table);
        });
        tableDropList.getSelectionModel().select(0);
        currentTable.setText(tableDropList.getSelectionModel().getSelectedItem());

        // tableDropList.setDisable(true);
        selectedItem = tableDropList.getSelectionModel().getSelectedItem();

        // 初始化dropList监听
        tableDropList.getSelectionModel().selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    selectedItem = tableDropList.getSelectionModel().getSelectedItem();
                    // 更换表
                    currentTable.setText(selectedItem);
                    saveTableName();
                    // tableDropList.setDisable(true);
                });
    }

    /**
     * 刷新 DropList
     *
     * @param wordService
     * @author AryanKH
     * @date 2023/5/30 12:56
     */
    private void refreshDropList(WordService wordService) {
        // 检查数据库有多少张表, 并设置到dropList中
        tableDropList.getItems().clear();
        List<String> tables = wordService.checkAllTableAndCount();
        tables.iterator().forEachRemaining(table -> {
            tableDropList.getItems().add(table);
        });
    }

    /**
     * 选项table
     *
     * @param event
     * @author AryanKH
     * @date 2023/5/30 12:56
     */
    @FXML
    void onSelectTable(MouseEvent event) {
        WordService wordService = SpringUtil.getBean(WordService.class);
        if (event.getClickCount() == MouseClickConstants.DOUBLE_CLICK) {
            TextInputDialog dialog = new TextInputDialog("NEW");
            dialog.setTitle("新建存档");
            dialog.setHeaderText("请输入一个新存档名");
            dialog.setContentText("快点输入: ");
            Optional<String> result = dialog.showAndWait();
            // The Java 8 way to get the response value (with lambda expression).
            result.ifPresent(tableName -> {
                List<String> tables = wordService.checkAllTableAndCount();
                tables.iterator().forEachRemaining(tableNameInDb -> {
                    if (!tableName.equals(tableNameInDb)) {
                        wordService.createTable(tableName);
                    } else {
                        textBox.setText("已添加该表: " + tableName);
                    }
                });

            });

        } else {
            tableDropList.setDisable(!tableDropList.isDisable());
        }

    }

    @FXML
    void onFreshDropList(MouseEvent event) {
        refreshDropList(SpringUtil.getBean(WordService.class));
    }


    @FXML
    void onCount(MouseEvent event) {
        WordService wordService = SpringUtil.getBean(WordService.class);
        textBox.setText(wordService.getCountWithTableName(selectedItem).toString());
    }

    /**
     * 中文查找
     *
     * @param event
     * @author AryanKH
     * @date 2023/4/25 16:42
     */
    @FXML
    void onFind(MouseEvent event) {
        WordService wordService = SpringUtil.getBean(WordService.class);
        try {
            List<ReloadWordEntity> wordEntities = wordService
                    .getWordByChineseWithTableName(explanationBox.getText(), selectedItem);

            if (!wordEntities.isEmpty()) {
                // 生成一个有文本域的alert
                TextArea textArea = new TextArea();
                textArea.setEditable(false);
                textArea.setWrapText(true);
                StringBuffer stringBuffer = new StringBuffer();

                wordEntities.forEach(wordEntity -> stringBuffer
                        .append(wordEntity.getWord()).append(" ")
                        .append(wordEntity.getExplanation()).append("\n"));
                textArea.setText(stringBuffer.toString());
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("Click to see totally content: ");
                GridPane gridPane = new GridPane();
                gridPane.add(textArea, 0, 1);
                alert.getDialogPane().setExpandableContent(gridPane);
                alert.showAndWait();
            } else {
                textBox.setText("没有此单词");
            }
        } catch (Exception e) {
            // System.out.println(e.getMessage());
            textBox.setText("中文查询出现错误");
        }
    }

    /**
     * 英文查找
     *
     * @param event
     * @author AryanKH
     * @date 2023/4/25 17:04
     */
    @FXML
    void onSearch(MouseEvent event) {
        WordService wordService = SpringUtil.getBean(WordService.class);
        try {
            ReloadWordEntity word = wordService
                    .getWordByEnglishWithTableName(inputBox.getText().trim(), selectedItem);
            textBox.setText(word.getWord().trim() + "   " + word.getExplanation());
            // 打印日志 lock synchronize
        } catch (Exception e) {
            textBox.setText("No such word");
        }
    }

    /**
     * 字段添加
     *
     * @param event
     * @author AryanKH
     * @date 2023/4/25 17:04
     */
    @FXML
    void onAdd(MouseEvent event) {
        WordService wordService = SpringUtil.getBean(WordService.class);
        int flag = wordService.addWordWithTableName(inputBox.getText().trim(),
                explanationBox.getText().trim(),
                selectedItem.trim());
        if (flag > 0) {
            textBox.setText("Have added : " + inputBox.getText());
            inputBox.clear();
            explanationBox.clear();
        } else if (flag == 0) {
            textBox.setText("Check you whether input explanation and word");
        } else if (flag == -1) {
            textBox.setText("You had added that word : " + inputBox.getText());
        }

        // 快捷键 enter + control
        KeyCombination keyCombination = new KeyCodeCombination(KeyCode.ENTER, KeyCombination.CONTROL_DOWN);
        stage.getScene().getAccelerators().put(keyCombination, () -> {
            int flag1 = wordService.addWordWithTableName(inputBox.getText().trim(),
                    explanationBox.getText().trim(),
                    selectedItem.trim());
            if (flag1 > 0) {
                textBox.setText("Have added : " + inputBox.getText());
                inputBox.clear();
                explanationBox.clear();
            } else if (flag1 == 0) {
                textBox.setText("Check you whether input explanation and word");
            } else if (flag1 == -1) {
                textBox.setText("You had added that word : " + inputBox.getText());
            }
            inputBox.requestFocus();
        });
        inputBox.requestFocus();
    }

    @FXML
    void onShowRandomWindow(MouseEvent event) {
        TaxStartApplication.showView(RandomWordView.class);
    }

    @FXML
    void onStepToPatch(MouseEvent event) {
        TaxStartApplication.showView(ChangeView.class);
    }

    @FXML
    void onToTranslation(MouseEvent event) {
        TaxStartApplication.showView(TranslationView.class);
    }


}
